<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        list-style: none;
      }
      .box {
        width: 300px;
        border: 1px solid #000;
        box-sizing: border-box;
        margin: 0 auto;
      }
      .box > .head {
        display: flex;
        justify-content: space-between;
      }
      .box > .head > li {
        flex: 1;
        text-align: center;
        border: 1px solid #000;
        box-sizing: border-box;
      }
      .main {
        height: 100px;
      }
      .active {
        background-color: cadetblue;
      }
      .main > div {
        display: none;
      }
      .main > .block {
        display: block;
      }
      .main {
        background-color: cyan;
      }
    </style>
  </head>
  <body>
    <div class="box">
      <ul class="head">
        <li class="active">标题一</li>
        <li>标题二</li>
        <li>标题三</li>
      </ul>
      <div class="main">
        <div class="contentBox contentBox1 block">标题内容1</div>
        <div class="contentBox contentBox2">标题内容2</div>
        <div class="contentBox contentBox3">标题内容3</div>
      </div>
    </div>

    <script>
      let list = document.querySelectorAll(".box > .head > li");
      let main = document.querySelector(".main");
      let contentBox = document.querySelectorAll(".main>.contentBox");
      let newcontentBox = [];
      let lastIndex = 0; //设置上一个操作的下标

      list.forEach(function (item, index) {
        item.onclick = function () {
          //清除上一个点击的标题的类名
          list[lastIndex].classList.remove("active");
          //为本次点击的标题添加类名
          item.classList.add("active");

          contentBox.forEach(function (item, index) {
            newcontentBox.push(item);
          });

          //清除上一个点击的内容的类名block
          newcontentBox[lastIndex].classList.remove("block");
          //为本次点击的内容添加类名block
          newcontentBox[index].classList.add("block");
          //把相对应的内容放入容器
          main.appendChild(newcontentBox[index]);

          //保存操作完毕之后的下标
          lastIndex = index;
        };
      });
    </script>
  </body>
</html>
